#include <stdio.h>
#include <errno.h>
#include "pb_decode.h"
#include "pb_encode.h"
#include "UserInformation.pb.h"

#define DATA_BUFFER_SIZE    1024

static int pack_user_data(uint8_t *buffer)
{
    //Initialize the UserInformation structure;
    UserInformation userInfo = UserInformation_init_zero;

    // Initialize buffer
    memset(buffer, 0, DATA_BUFFER_SIZE);

    strcpy(userInfo.name, "Benjamin");
    userInfo.age = 18; 
    strcpy(userInfo.phone, "0755-12345678");
    userInfo.stat = UserStatus_IDLE;
    strcpy(userInfo.email, "ZhangSan@123.com");

    // encode userInfo data
    pb_ostream_t enc_stream;
	enc_stream = pb_ostream_from_buffer(buffer, DATA_BUFFER_SIZE);
	if (!pb_encode(&enc_stream, UserInformation_fields, &userInfo))
	{
		//encode error happened
		printf("pb encode error in %s [%s]\n", __func__,PB_GET_ERROR(&enc_stream));
		return -1;
	}

    return enc_stream.bytes_written;
}

static int unpack_user_data(const uint8_t *buffer, size_t len)
{
    UserInformation userInfo;

    // decode userInfo data
	pb_istream_t dec_stream;
	dec_stream = pb_istream_from_buffer(buffer, len);
	if (!pb_decode(&dec_stream, UserInformation_fields, &userInfo))
	{
		printf("pb decode error in %s\n", __func__);
		return -1;
	}

    printf("Unpack: %s %d %s %s\n", userInfo.name, userInfo.age, userInfo.phone, userInfo.email);

    return 0;
}

int main()
{
    uint8_t buffer[DATA_BUFFER_SIZE];

    int lenght = pack_user_data(buffer);
    if(lenght<0){
        printf("main: pack_user_data is fail!!!\n");
        return -1;
    }
    printf("User data len: %d\n",lenght);
    unpack_user_data(buffer, lenght);
	
	return 0;
}


